import { getFile } from '@luzhongk/upload'
import { upload } from 'qiniu-js'
import * as Api from '../api/upload-token'

export async function toUpload(file, observer) {
  let token
  try {
    token = await Api.getToken()
  } catch (e) {
    observer.error(e)
    return Promise.reject(e)
  }
  // 并发5个上传
  const config = { concurrentRequestLimit: 5, disableStatisticsReport: true }
  // file, key, token, putExtra, config
  const observable = upload(file, undefined, token, undefined, config)
  const subscription = observable.subscribe(observer)
  return subscription
}

// accept { next, error, complete }
export async function uploadSingleFile(accept = 'image/*', observer) {
  const file = await getFile({ accept })
  return toUpload(file, observer)
}
